<template>
  <div class="resizable-layout" :class="{ 'vertical-layout': isVertical }">
    <div class="left-panel" :style="isVertical ? {} : { width: leftWidth + 'px' }">
      <slot name="left"></slot>
    </div>

    <div v-if="!isVertical" class="divider" @mousedown="startDrag"></div>

    <div class="right-panel">
      <slot name="right"></slot>
    </div>
  </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, onUnmounted, computed } from 'vue'

const props = withDefaults(defineProps<{
  initialLeftWidth?: number,
  minLeftWidth?: number,
  maxLeftWidth?: number,
  breakpoint?: number,
  isVertical?: boolean
}>(), {
  initialLeftWidth: 200,
  minLeftWidth: 100,
  maxLeftWidth: 500,
  breakpoint: 1280,
  isVertical: false
})

const leftWidth = ref(props.initialLeftWidth)
const windowWidth = ref(window.innerWidth)
let isDragging = false
let startX = 0
let startWidth = 0

// 计算是否应该垂直布局
const isVertical = computed(() => props.isVertical || windowWidth.value < props.breakpoint)

const startDrag = (e) => {
  if (isVertical.value) return
  isDragging = true
  startX = e.clientX
  startWidth = leftWidth.value
  document.body.style.cursor = 'col-resize'
  document.body.style.userSelect = 'none'
}

const onDrag = (e) => {
  if (!isDragging || isVertical.value) return
  const dx = e.clientX - startX
  let newWidth = startWidth + dx

  // 应用最小和最大宽度限制
  newWidth = Math.max(props.minLeftWidth, newWidth)
  newWidth = Math.min(props.maxLeftWidth, newWidth)

  leftWidth.value = newWidth
}

const stopDrag = () => {
  isDragging = false
  document.body.style.cursor = ''
  document.body.style.userSelect = ''
}

const handleResize = () => {
  windowWidth.value = window.innerWidth
}

onMounted(() => {
  document.addEventListener('mousemove', onDrag)
  document.addEventListener('mouseup', stopDrag)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  document.removeEventListener('mousemove', onDrag)
  document.removeEventListener('mouseup', stopDrag)
  window.removeEventListener('resize', handleResize)
})

</script>

<style scoped>
.resizable-layout {
  display: flex;
  height: 100%;
  width: 100%;
  overflow: hidden;
}

/* 水平布局样式 */
.left-panel {
  height: 100%;
  overflow: auto;
  flex-shrink: 0;
}

.right-panel {
  flex-grow: 1;
  height: 100%;
  overflow: auto;
  background-color: #fff;
}

.divider {
  width: 8px;
  height: 100%;
  background-color: #fff;
  cursor: col-resize;
  flex-shrink: 0;
}

.divider:hover {
  background-color: #ccc;
}

/* 垂直布局样式 */
.resizable-layout.vertical-layout {
  flex-direction: column;
}

.resizable-layout.vertical-layout .left-panel,
.resizable-layout.vertical-layout .right-panel {
  width: 100% !important;
  height: auto;
  flex-grow: 1;
  flex-shrink: 1;
}
</style>